package com.suisung.shopsuite.sys.service.impl;

import com.suisung.shopsuite.pay.service.WeChatPayInfo;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class SmsServiceImpl {

    //2444608
    public void sendSmsByTencent(String phone, String remindTemplateId,String code) {
        String message = "";
        try {
            // 实例化一个认证对象
            Credential cred = new Credential(WeChatPayInfo.tencentSmsSecretId, WeChatPayInfo.tencentSmsSecretKey);

            // 实例化 SMS 的 client 对象
            SmsClient client = new SmsClient(cred, "ap-nanjing");

            // 实例化一个请求对象
            SendSmsRequest req = new SendSmsRequest();

            // 设置应用 ID
            req.setSmsSdkAppId(WeChatPayInfo.tencentSmsAppid);

            // 设置签名名称
            req.setSignName(WeChatPayInfo.tencentSmsSignName);

            // 设置模板 ID
            req.setTemplateId(remindTemplateId);

            /* 模板参数，按照实际模板填写
            例如模板内容为：
            "您预约的{1}还未完成购买，这是第{2}次提醒，请尽快完成购买以开始养殖。"
            */
            String[] templateParams= new String[]{};

            // 设置模板参数
            if(remindTemplateId.equals("2444608")){
                // 养殖购买通知
                templateParams = new String[]{code};
            }

            req.setTemplateParamSet(templateParams);

            // 设置手机号码，支持国内手机号
            String[] phoneNumbers = {phone};
            req.setPhoneNumberSet(phoneNumbers);

            // 发送短信
            SendSmsResponse res = client.SendSms(req);
            message = res.getSendStatusSet()[0].getMessage();
            // 处理响应
            if (!"Ok".equals(res.getSendStatusSet()[0].getCode())) {
                log.error("SmsServiceImpl sms 发送短信失败: 手机号={}, 原因={}", phone, message);
                throw new RuntimeException("发送短信失败: " + message);
            }

            log.info("SmsServiceImpl sms 发送短信成功: 手机号={}, 模板id={}，参数={}", phone, remindTemplateId,req.getTemplateParamSet());

        } catch (TencentCloudSDKException e) {
            log.error("SmsServiceImpl sms 发送短信异常: 手机号={}, 原因={}", phone, e.getMessage());
        }

    }
}
